package agh.sr.lab4.common.server;

import agh.sr.lab4.bank.server.BankManagerI;
import agh.sr.lab4.bank.server.BankOneToManyServantLocator;
import agh.sr.lab4.bank.server.BankOneToOneServantLocator;
import agh.sr.lab4.chat.server.ChatDataProvider;
import agh.sr.lab4.chat.server.ChatManagerI;
import agh.sr.lab4.chat.server.ChatServantLocator;
import agh.sr.lab4.chat.server.IChatDataProvider;
import agh.sr.lab4.common.utils.BankServerModes;
import agh.sr.lab4.common.utils.Config;

public class CommonServer {

	public void t1(String[] args) {
		int status = 0;
		Ice.Communicator ic = null;

		try {
			ic = Ice.Util.initialize(args);

			Ice.PluginManager pluginMgr = ic.getPluginManager();
			Ice.Plugin plugin = pluginMgr.getPlugin("IceSSL");
			IceSSL.Plugin sslPlugin = (IceSSL.Plugin) plugin;
			sslPlugin.setCertificateVerifier(new MyCertificateVerifier());

			Ice.ObjectAdapter commonAdapter = ic
					.createObjectAdapter("CommonAdapter");

			// bank manager side
			// init objects
			BankManagerI bankManager = new BankManagerI();
			Ice.Object bankManagerIceObject = bankManager;
			Ice.ServantLocator bankServantLocator = null;
			if (Config.BANK_SERVER_MODE == BankServerModes.OneServantToOneClient) {
				bankServantLocator = new BankOneToOneServantLocator();
			}else if (Config.BANK_SERVER_MODE == BankServerModes.OneServantToManyClients){
				bankServantLocator = new BankOneToManyServantLocator();
			}else{
				throw new Error("Bad bank-server-mode settings: " + Config.BANK_SERVER_MODE);
			}

			// register bank app in adapter
			commonAdapter.add(bankManagerIceObject,
					ic.stringToIdentity(Config.BANK_MANAGER_SERVANT));
			commonAdapter.addServantLocator(bankServantLocator,
					Config.BANK_CATEGORY);

			// chat manager side
			IChatDataProvider chatDataProvider = new ChatDataProvider();
			ChatManagerI chatManager = new ChatManagerI(chatDataProvider);
			Ice.Object chatManagerIceObject = chatManager;
			Ice.ServantLocator chatServantLocator = new ChatServantLocator();

			// register chat app in adapter
			commonAdapter.add(chatManagerIceObject,
					ic.stringToIdentity(Config.CHAT_MANAGER_SERVANT));
			commonAdapter.addServantLocator(chatServantLocator,
					Config.CHAT_CATEGORY);

			// run adapter
			commonAdapter.activate();

			System.out.println("SERVER READY");
			try {
				ic.waitForShutdown();
			} finally {
			}

			ic.waitForShutdown();
		} catch (Exception e) {
			System.err.println(e);
			status = 1;
		}
		if (ic != null) {
			// Clean up
			//
			try {
				ic.destroy();
			} catch (Exception e) {
				System.err.println(e);
				status = 1;
			}
		}
		System.exit(status);
	}

	public static void main(String[] args) {
		CommonServer app = new CommonServer();
		app.t1(args);
	}

}
